const { Sequelize, DataTypes, Op } = require('sequelize')

// 中文文档
// https://github.com/demopark/sequelize-docs-Zh-CN/tree/master

// 建立连接
const sequelize = new Sequelize(
    'node_test', 'root', 'guzhan321',
    {
        host: 'localhost',
        dialect: 'mysql'
    }
)

// 创建模型
const Order = sequelize.define(
    'order',
    {
        message: {
            type: DataTypes.STRING(255)
        },
        price: {
            type: DataTypes.FLOAT
        }
    },
    {
        // timestamps: false,
    }
)

;(async () => {
    // 同步表结构
    await sequelize.sync({ force: true })

    // 插入数据

    let data = await Order.create({
        message: 'mac',
        price: 12999
    })

    data = await Order.create({
        message: 'Iphone 12',
        price: 8999
    })

    data = await Order.create({
        message: 'Iphone 11',
        price: 6999
    })

    data = await Order.create({
        message: 'Iphone 10',
        price: 4999
    })

    // 删
    // await Order.destroy({ 
    //     where: {
    //         id: 1
    //     }
    //  })

    // 改
    // data.price = 1

    // await Order.update({
    //     price: 1
    // },{
    //     where: {
    //         id: 2
    //     }
    // })

    // 查
    data = await Order.findAll({
        where: {
            // 条件操作符
            // https://github.com/demopark/sequelize-docs-Zh-CN/blob/master/core-concepts/model-querying-basics.md#%E6%93%8D%E4%BD%9C%E7%AC%A6
            // price: {
                // [Op.lt]: 7500
                // [Op.eq]: 4999
            // }
            // message: {
            //     [Op.like]: '%a%'
            // }
        },
        order: [
            ['price', 'desc']
        ]
    })
    console.log(JSON.stringify(data, null, 2))

})();
